<template>
  <div class="user-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="searchForm.email" placeholder="请输入邮箱" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.enabled" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" icon="Search">搜索</el-button>
          <el-button @click="resetSearch" icon="Refresh">重置</el-button>
          <el-button type="success" @click="refreshData" icon="RefreshRight">刷新</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="action-card">
      <el-button 
        v-if="hasPermission('system:user:create')"
        type="primary" 
        @click="showCreateDialog"
        icon="Plus"
      >
        新增用户
      </el-button>
    </el-card>

    <!-- 表格区域 -->
    <el-card>
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="fullName" label="姓名" width="120" />
        <el-table-column prop="enabled" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.enabled ? 'success' : 'danger'">
              {{ row.enabled ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="roles" label="角色" min-width="150">
          <template #default="{ row }">
            <el-tag v-for="role in row.roles" :key="role.id" class="mr-1">
              {{ row.displayName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="hasPermission('system:user:edit')"
              type="primary" 
              size="small" 
              icon="Edit"
              @click="editUser(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="hasPermission('system:user:delete')"
              type="danger" 
              size="small" 
              icon="Delete"
              @click="deleteUser(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { usePermission } from '@/composables/usePermission'
import api from '@/utils/request'

const { hasPermission } = usePermission()

const loading = ref(false)
const tableData = ref([])

const searchForm = ref({
  username: '',
  email: '',
  enabled: null
})

const pagination = ref({
  page: 1,
  size: 10,
  total: 0
})

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.page - 1,
      size: pagination.value.size,
      ...searchForm.value
    }
    
    const response = await api.get('/users', { params })
    tableData.value = response.data.content || []
    pagination.value.total = response.data.totalElements || 0
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.value.page = 1
  fetchData()
}

const resetSearch = () => {
  searchForm.value = {
    username: '',
    email: '',
    enabled: null
  }
  handleSearch()
}

const refreshData = () => {
  fetchData()
}

const handleSizeChange = () => {
  pagination.value.page = 1
  fetchData()
}

const handleCurrentChange = () => {
  fetchData()
}

const showCreateDialog = () => {
  // TODO: 实现创建用户对话框
  ElMessage.info('创建用户功能待实现')
}

const editUser = (user: any) => {
  // TODO: 实现编辑用户对话框
  ElMessage.info('编辑用户功能待实现')
}

const deleteUser = async (user: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 ${user.username} 吗？`, '确认删除', {
      type: 'warning'
    })
    
    await api.delete(`/users/${user.id}`)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.search-card, .action-card {
  margin-bottom: 20px;
}

.mr-1 {
  margin-right: 4px;
}
</style>


